package com.icehand.common.result;

import com.alibaba.fastjson.JSON;
import com.icehand.common.code.CodeEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

/**
 * @author icehand
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BizResult<T> implements Serializable {
    /**
     * 自定义状态码
     */
    private int code = 0;

    /**
     * 返回给前端展示的信息
     */
    private String msg;

    /**
     * 附加信息
     */
    private String extra;

    /**
     * body
     */
    private T data;

    /**
     * 时间戳
     */
    private Date timestamp = new Date();

    public BizResult(T data) {
        this.data = data;
    }

    public BizResult(int code, String msg) {
        this(code,msg,null);
    }

    public BizResult(int code, String msg, String extra) {
        this.code = code;
        this.msg = msg;
        this.extra = extra;
    }

    public BizResult(CodeEnum<Integer> codeEnum){
        this.code = codeEnum.getCode();
        this.msg = codeEnum.getMsg();
    }

    public void error(CodeEnum<Integer> codeEnum) {
        error(codeEnum.getCode(),codeEnum.getMsg());
    }

    public void error(int code, String msg){
        error(code, msg,null);
    }

    public void error(int code, String msg, String extra){
        this.code = code;
        this.msg = msg;
        this.extra = extra;
    }

    public void putData(T data){
        this.data = data;
    }

    public boolean isSuccess(){
        return 0 == code;
    }

    public String toJSONString(){
        return JSON.toJSONString(this);
    }
}
